package utils

import (
	"fmt"
	"strconv"
)

// 通用 string 提取（自动支持 string, int, float, bool 等）
func GetStringFromMap(m map[string]any, key string) string {
	if val, ok := m[key]; ok {
		switch v := val.(type) {
		case string:
			return v
		case []byte:
			return string(v)
		case fmt.Stringer:
			return v.String()
		default:
			return fmt.Sprintf("%v", v)
		}
	}
	return ""
}

// 提取 int
func GetIntFromMap(m map[string]any, key string) int {
	valStr := GetStringFromMap(m, key)
	if valStr == "" {
		return 0
	}
	num, err := strconv.Atoi(valStr)
	if err != nil {
		return 0
	}
	return num
}

// 提取 int64
func GetInt64FromMap(m map[string]any, key string) int64 {
	valStr := GetStringFromMap(m, key)
	if valStr == "" {
		return 0
	}
	num, err := strconv.ParseInt(valStr, 10, 64)
	if err != nil {
		return 0
	}
	return num
}

// 提取 uint64
func GetUint64FromMap(m map[string]any, key string) uint64 {
	valStr := GetStringFromMap(m, key)
	if valStr == "" {
		return 0
	}
	num, err := strconv.ParseUint(valStr, 10, 64)
	if err != nil {
		return 0
	}
	return num
}

// 提取 float64
func GetFloat64FromMap(m map[string]any, key string) float64 {
	valStr := GetStringFromMap(m, key)
	if valStr == "" {
		return 0
	}
	num, err := strconv.ParseFloat(valStr, 64)
	if err != nil {
		return 0
	}
	return num
}

// 提取 bool
func GetBoolFromMap(m map[string]any, key string) bool {
	valStr := GetStringFromMap(m, key)
	if valStr == "" {
		return false
	}
	val, err := strconv.ParseBool(valStr)
	if err != nil {
		return false
	}
	return val
}
